import React from 'react'
import { connect } from 'dva'
import { Form ,Modal,message,Upload,Button,Tabs,Row ,Col,Select,Input,Radio } from 'antd'
import { Link, hashHistory } from 'dva/router'
import config from 'config/config'
import FlagBtn from 'widget/FlagBtn/FlagView'
import { mapStateToProps } from 'utils/view_utils'
import styles from './monthReportStyle.less'
import ListPage from 'widget/PageTmpl/ListPageQiance'
import classnames from 'classnames/bind';
import Uploader from 'widget/Upload'

import moment from 'moment'
let cx=classnames.bind(styles);
const confirm = Modal.confirm;
const { TabPane } = Tabs;
const { TextArea } = Input;
const FormItem = Form.Item
const formItemLayoutPro = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
  };
function timestampToTime(timestamp) {
  var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-';
  var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
  var D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
  var h = (date.getHours() < 10 ? '0'+date.getHours() : date.getHours()) + ':';
  var m = (date.getMinutes() < 10 ? '0'+date.getMinutes() : date.getMinutes()) + ':';
  var s = (date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds());
    return Y+M+D+h+m+s;
}

const monthReportView = function({dispatch, model, form}) {
  // 表单的子函数
  const {resetFields, getFieldDecorator, validateFields, setFieldsValue,validateFieldsAndScroll} = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  // modelObj.xxx获取model中状态机的值
  let {exportXlsFlag,url,visible,cityList,areaList,tabsType,biz,biz1,biz2,btnLoading} = modelObj
  let pageProps1 = { //市场月报
    // ---------- 界面部分 ----------
    ui: {
      // 页面接口地址
      api_url: `${config.aheadPlan}admin/monthlyPeport/monthlyPeport/list`,
      // 接口方式
      method: "GET",
      // "data_field_name":"data",
      app: "",
      // 接口参数
      params: {
        pageSize:10,
        pageNo:1,
      },
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      mockData: null,
      // 查询栏
      search_bar: {
        fields: [
          {
            en_name: 'month',
            zh_name: '统计月份',
            elem_type: 'month',
            elem_valid_type: 'string'
          },
          {
            en_name: 'areaCode',
            zh_name: '区域',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: areaList
          }, 
          {
            en_name: 'cityCode',
            zh_name: '城市',
            elem_type: 'SelectFilter',
            elem_valid_type: 'string',
            showSearch: true,
            cmpt_items: cityList,
            onFocus:()=>{
              if(biz1.queryForm && biz1.queryForm.areaCode){ 
                dispatch({
                  type: `${namespace}/findByCity`,
                  payload: { areaId:biz1.queryForm.areaCode }
              })
              }
            },
          },
          {
            en_name: 'quantityRatio',
            zh_name: '量价情况',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: [
              {
                  value: '量价齐升',
                  label: '量价齐升'
              }, 
              {
                  value: '量升价平/跌',
                  label: '量升价平/跌'
              },
              {
                  value: '量平价升/跌',
                  label: '量平价升/跌'
              },
              {
                  value: '量价齐平',
                  label: '量价齐平'
              },
              {
                  value: '量价齐跌',
                  label: '量价齐跌'
              },
              {
                  value: '量跌价升/平',
                  label: '量跌价升/平'
              }
          ]
          },
          {
            en_name: 'monthlyStatus',
            zh_name: '状态',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: [
                {
                    value: '0',
                    label: '未提交'
                }, 
                {
                    value: '1',
                    label: '已提交'
                }
            ],
          },
        ],
        searchHandler: () => { // 自定义搜索按钮回调函数，点击搜索时触发
          console.log('search click')
        },
        resetHandler: () => { // 自定义重置按钮回调函数，点击重置时触发
          console.log('reset click')
        },
        searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
          console.log('search finish', params)
        },
        pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
          'channel',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
        ]
      },
      // 数据表格  序号 是否生效 项目名称  佣金方案名称 方案生效日期 方案失效日期 审批人 审批通过日期   提交人 提交日期  创建人 创建日期
      table:
        {
          rowSelectionInfo: {
            type: 'checkbox',
          },
          status_params: "status=0",
          status_text: "全部",
          // 表头字段列表
          scroll: { x: 2400},
          fields: [
            {
              en_name: "month",
              zh_name: "统计月份",width: 130,
              render:(a, item, index, d, e, f)=>{
                  return item.month
              }
            },
            {
              en_name: "area",
              zh_name: "区域",
              width: 160,
            },
            {
              en_name: "city",
              zh_name: "城市",
              width: 120,
            },
            {
              en_name: "region",
              zh_name: "县/区",
              width: 120,
              render: (a, item, index, d, e, f) => {
                if(item.region){
                  return item.region
                }else{
                  return "-"
                }
              },
            },
            {
              en_name: "addAcreage",
              zh_name: "新供面积(m²)",
              width: 140,
              sorter: (a, b) => a.addAcreage - b.addAcreage,
            },
            {
              en_name: "transactionAcreage",
              zh_name: "成交面积(m²)",
              sorter: (a, b) => a.transactionAcreage - b.transactionAcreage,
            },
            {
              en_name: "acreageRatio",
              zh_name: "面积环比(%)",
              sorter: (a, b) => a.acreageRatio - b.acreageRatio,
              render: (a, item, index, d, e, f) => {
                return item.acreageRatio + '%'
              },
            },
            {
              en_name: "averagePrice",
              zh_name: "成交均价(元/m²)",
              sorter: (a, b) => a.averagePrice - b.averagePrice,
            }, 
            {
              en_name: "averageRatio",
              zh_name: "均价环比(%)",
              sorter: (a, b) => a.averageRatio - b.averageRatio,
              render: (a, item, index, d, e, f) => {
                  return item.averageRatio + '%'
              },
            },
            {
              en_name: "quantityRatio",
              zh_name: "量价情况",
              render: (a, item, index, d, e, f) => {
                  return item.quantityRatio
              },
            },
            {
              en_name: "salesAmount",
              zh_name: "销售金额(元)",
              sorter: (a, b) => a.salesAmount - b.salesAmount,
            },
            {
              en_name: "createBy",
              zh_name: "创建人",
              render: (a, item, index, d, e, f) => {
                  return item.createBy?item.createBy:'-'
              },
            },
            {
              en_name: "createTime",
              zh_name: "创建时间",
              render: (a, item, index, d, e, f) => {
                  return item.createTime?item.createTime:'-'
              },
            },
            {
              en_name: "updateBy",
              zh_name: "提交人",
              render: (a, item, index, d, e, f) => {
                  return item.updateBy?item.updateBy:'-'
              },
            },
            {
              en_name: "updateTime",
              zh_name: "提交时间",
              render: (a, item, index, d, e, f) => {
                return item.updateTime?item.updateTime:'-'
              },
            },
            {
              en_name: "monthlyStatus",
              zh_name: "状态",width: 100,fixed:'right',
              render: (a, item, index, d, e, f) => {
                if(item.monthlyStatus == '0'){
                  return '未提交'
                }else if(item.monthlyStatus == '1'){
                  return '已提交'
                }else{
                  return ''
                }
              },
            },
            {
              en_name: "edit",
              zh_name: "操作",
              width:110,
              fixed:'right',
              render: (a, item, index, d, e, f) => {
                return (
                  <span>
                      <FlagBtn node={<a onClick={() => submitContent(item,'市场')}>{item.monthlyStatus==1?'撤回':'提交'}<span className="ant-divider" /></a>} btnId={'17050101'}> </FlagBtn>
                      {item.monthlyStatus == '0'&&<FlagBtn node={<a onClick={() => checkOrEditSkip('edit',item,'市场')}>编辑<span className="ant-divider" /></a>} btnId={'17050103'}> </FlagBtn>}
                      {item.monthlyStatus == '1'&&<FlagBtn node={<a onClick={() => checkOrEditSkip('check',item,'市场')}>查看<span className="ant-divider" /></a>} btnId={'17050103'}> </FlagBtn>}
                      <FlagBtn node={<a onClick={() => deleteContent(item)}><span style={{color: item.monthlyStatus==1?'#999':'#0877FD'}}>删除</span></a>}> </FlagBtn>
                  </span>
                )
              },
            }
          ],
        },
      // 操作栏
      action_bar: [
        {
          rowSelection: [],
          render: () => {
            return <Input hidden/>
          },
          onClick: (e, row) => {
          }
        },
      ]
    },
  }
  let pageProps2 = { //集团周月报
    // ---------- 界面部分 ----------
    ui: {
      // 页面接口地址
      api_url: `${config.aheadPlan}admin/groupMonth/groupMonth/list`,
      // 接口方式
      method: "GET",
      // "data_field_name":"data",
      app: "",
      // 接口参数
      params: {
        pageSize:10,
        pageNo:1,
      },
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      mockData: null,
      // 查询栏
      search_bar: {
        fields: [
        {
            en_name: 'month',
            zh_name: '统计月份',
            elem_type: 'month',
            elem_valid_type: 'string'
          },
          {
            en_name: 'title',
            zh_name: '月报标题',
            elem_type: 'Input',
            elem_valid_type: 'string',
          },
          {
            en_name: 'status',
            zh_name: '状态',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: [
                {
                    value: '1',
                    label: '已发布'
                },
                {
                    value: '0',
                    label: '未发布'
                }
            ],
          },
        ],
        searchHandler: () => { // 自定义搜索按钮回调函数，点击搜索时触发
          console.log('search click')
        },
        resetHandler: () => { // 自定义重置按钮回调函数，点击重置时触发
          console.log('reset click')
        },
        searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
          console.log('search finish', params)
        },
        pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
          'channel',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
        ]
      },
      // 数据表格  序号 是否生效 项目名称  佣金方案名称 方案生效日期 方案失效日期 审批人 审批通过日期   提交人 提交日期  创建人 创建日期
      table:
        {
          status_params: "status=0",
          status_text: "全部",
          // 表头字段列表
          scroll: { x: 1000},
          fields: [
            {
              en_name: "ruleNo",
              zh_name: "编号",
              width: 60,
              render: (a, item, index, d, e, f) => {
                return index+1
              },
            },
            {
              en_name: "month",
              zh_name: "统计月份",
            },
            {
              en_name: "title",
              zh_name: "月份标题",
            },
            {
              en_name: "createBy",
              zh_name: "创建人",
              render: (a, item, index, d, e, f) => {
                  return item.createBy?item.createBy:'-'
              },
            },
            {
              en_name: "createTime",
              zh_name: "创建时间",
              render: (a, item, index, d, e, f) => {
                  return item.createTime?item.createTime:'-'
              },
            },
            {
              en_name: "updateBy",
              zh_name: "提交人",
              render: (a, item, index, d, e, f) => {
                  return item.updateBy?item.updateBy:'-'
              },
            },
            {
              en_name: "updateTime",
              zh_name: "提交时间",
              render: (a, item, index, d, e, f) => {
                return item.updateTime?item.updateTime:'-'
              },
            },
            {
              en_name: "status",
              zh_name: "发布状态",
              fixed:'right',
              width: 110,
              render:(a, item, index, d, e, f)=>{
                if(item.status=='1'){
                  return '已发布'
                }else if(item.status=='0'){
                  return '未发布'
                }
              }
            },
            {
              en_name: "edit",
              zh_name: "操作",
              width:110,
              fixed:'right',
              render: (a, item, index, d, e, f) => {
                return (
                  <span>
                      <FlagBtn node={<a onClick={() => exportXls(item)}>导出<span className="ant-divider" /></a>} btnId={'17050204'}> </FlagBtn>
                      <FlagBtn node={<a onClick={() => updateCancel(item.id)}>预览<span className="ant-divider" /></a>} btnId={'17050204'}> </FlagBtn>
                      <FlagBtn node={<a onClick={() => submitContent(item,'集团')}>{item.status==1?'撤回': '发布'}<span className="ant-divider" /></a>} btnId={'17050201'}> </FlagBtn>
                      {item.status=='0'&&<FlagBtn node={<a onClick={() => checkOrEditSkip('edit',item,'集团')}>编辑</a>} btnId={'17050203'}> </FlagBtn>}
                      {item.status=='1'&&<FlagBtn node={<a onClick={() => checkOrEditSkip('check',item,'集团')}>查看</a>} btnId={'17050203'}> </FlagBtn>}
                  </span>
                )
              },
            }
          ],
        },
      // 操作栏
      action_bar: []
    },
  }

  function exportXls(item){
    dispatch({
      type: `${namespace}/exportXls`,
      payload: {item}
  })
  }
  //编辑
   function checkOrEditSkip(type,item,name){
    if(name == '市场'){
      hashHistory.push({
        pathname: '/home/predictManage/monthReportDetail',
        query: {actionType: type, id:item.id }
      })
    }
    if(name == '集团'){
      hashHistory.push({
        pathname: '/home/predictManage/groupMonthReportDetail',
        query: {actionType: type, id:item.id }
      })
    }
  }

  function deleteContent(item){
    if(item&&item.monthlyStatus=='1'){
      message.warning('不能删除已提交的月报')
      return
    }
    let params = item
    confirm({
      title: '删除确认',
      content: '您真的要删除此条信息吗?',
      okText: '确认',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: `${namespace}/deleteFun`,
          payload: {params}
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  // 跳转
  function goOtherConfigAdd(type){
    if(type == '市场'){
      hashHistory.push({
        pathname: '/home/predictManage/monthReportDetail',
        query: {}
      });
    }
    if(type == '集团'){
      hashHistory.push({
        pathname: '/home/predictManage/groupMonthReportDetail',
        query: {}
      })
    }
  }

  //撤回
  function submitContent(item,type){
      let temptype
      if(type == '市场')temptype = item.monthlyStatus == '1'?'撤回':'提交'
      if(type == '集团')temptype = item.status == '1'?'撤回':'发布'
      confirm({
        title: temptype+'确认',
        content: '您真的要'+temptype+'此条信息吗?',
        okText: '确认',
        okType: 'primary',
        cancelText: '取消',
        onOk() {
          dispatch({
            type: `${namespace}/submitContent`,
            payload: {params:item,type:type}
          })
        },
        onCancel() {
          console.log('Cancel');
        },
      });
  }

  //切换tabs
  function tabsChange(key) {
    tabsType = key
    dispatch({
        type: `${namespace}/updateStore`,
        payload: { tabsType }
    })
  }
  function updateCancel(id){
    visible = !visible
    if(config.ENV === 'prod'){
      url = "https://ms.mideazy.com/qianceH5/dist/#/phosphor/PhosphorPage?stack-key=9b4c665c"+ "&id="+id + "&type=2&token="+ localStorage.getItem("username")
    }else{
      url = "https://msuat.mideazy.com/qianceH5/dist/#/phosphor/PhosphorPage?stack-key=9b4c665c"+ "&id="+id + "&type=2&token="+ localStorage.getItem("username")
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { visible,url }
    })
  }
  function submitFun(type){
    dispatch({
      type: `${namespace}/submitContent`,
      payload: {type:type}
    })
  }

  if (!!modelObj.biz1) {
    pageProps1.biz = modelObj.biz1
    pageProps1.biz.syncBackCbf = (biz) => {
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { biz1:biz }
      })
    }
  }
  if (!!modelObj.biz2) {
    pageProps2.biz = modelObj.biz2
    pageProps2.biz.syncBackCbf = (biz) => {
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { biz2:biz }
      })
    }
  }

  return (
    <div className='public_listMain'>
        <div className={"functionButton"}>
            <FlagBtn node={<Button style={{display: tabsType=='1'?"inline-block": 'none',marginRight: '12px'}} type='primary' onClick={e => submitFun('多选提交')} loading={btnLoading}>提交</Button>} btnId={'17050101'}> </FlagBtn>
            <FlagBtn node={<Button style={{display: tabsType=='1'?"inline-block": 'none'}} type='primary' onClick={e => goOtherConfigAdd('市场')}>新增</Button>} btnId={'17050102'}> </FlagBtn>
            <FlagBtn node={<Button style={{display: tabsType=='2'?"inline-block": 'none'}} type='primary' onClick={e => goOtherConfigAdd('集团')}>新增</Button>} btnId={'17050202'}> </FlagBtn>
        </div>
       {tabsType&&<Tabs  onChange={tabsChange} animated={false} activeKey={tabsType} className='configuration-center-tabs'>
            <TabPane tab="市场月报" key="1">
                <ListPage pageProps={pageProps1}/>
            </TabPane>
            <TabPane tab="集团月报" key="2">
                <ListPage pageProps={pageProps2}/>
            </TabPane> 
        </Tabs>}
        <Modal
          width='655px'
          visible={visible}
          destroyOnClose={true}
          onCancel={() => { updateCancel() }}
          footer={null}
        >
          <div style={{padding:'0 116px'}}>
            <div className={cx('Xphone_box')}>
				      <iframe id="ifra" name="ifra" width="100%" height="667px" src={url}></iframe>
            </div>
          </div>
        </Modal>
    </div>
  )
}
// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(monthReportView))
